package control;
import java.io.Serializable;
import java.util.List;

import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.component.UIComponent;
import javax.faces.component.UIParameter;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;

import model.Artigo;
import business.ArtigoDAO;

@ManagedBean(name="artigoHandler")
@SessionScoped

public class ArtigoHandler implements Serializable {
	private static final long serialVersionUID = 1L;
	private ArtigoDAO artigoDAO = ArtigoDAO.getInstance();
	private Artigo artigo = new Artigo();
	private boolean emEdicao = false;
	
	public ArtigoDAO getArtigoDAO() {
		return this.artigoDAO;
	}
	public void setArtigoDAO(ArtigoDAO artigoDAO) {
		this.artigoDAO = artigoDAO;
	}
	public Artigo getArtigo() {
		return this.artigo;
	}
	public void setArtigo(Artigo artigo) throws Exception {
		this.artigo = artigo;
	}
	public String novo()	{
		this.artigo = new Artigo();
		this.emEdicao = true;
		return "artigoManter";
	}
	
	public String salvar(){
		this.artigo.setAreaAtuacaoId(1);
		this.artigoDAO.salvar(this.artigo);
		FacesContext context = FacesContext.getCurrentInstance();
		context.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Dados salvos com sucesso!",""));
		this.emEdicao = false;
		return "artigoManter";
	}
	
	public void editar(ActionEvent event) throws Exception {
		UIComponent link = event.getComponent();
		UIParameter param = (UIParameter) link.findComponent("editarArtigoParam");
		this.artigo = (Artigo)param.getValue();
		this.emEdicao = true;
	}
	
	public void excluir(ActionEvent event)	{
	    UIComponent link = event.getComponent();
		UIParameter param = (UIParameter) link.findComponent("excluirArtigoParam");
		Integer id = (Integer) param.getValue();
		this.artigoDAO.remover(id);
		this.artigo = new Artigo();
		this.emEdicao = false;
	}
	
	public List<Artigo> getArtigos()	{
		List<Artigo> itens = this.artigoDAO.listar();
		return itens;
	}
	
	public boolean getEmEdicao() {
		return this.emEdicao;
	}
	public void setEmEdicao(boolean emEdicao) {
		this.emEdicao = emEdicao;
	}
	public boolean getEmNavegacao() {
		return !this.emEdicao;
	}
}
